package com.xiebishe.mylibrary.net.okhttp;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.webkit.CookieManager;


import com.xiebishe.mylibrary.base.MyApplication;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okio.Buffer;

class CommonInterceptor implements Interceptor {

    private CookieManager cookieManager = CookieManager.getInstance();
    private ThreadLocal<Buffer> bufferThreadLocal = new ThreadLocal<>();

    @SuppressLint("NewApi")
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl currUrl = request.url();
        String url = currUrl.toString();
        /* ADD COOKIE*/
        String cookie = cookieManager.getCookie(url);
        Request.Builder builder = request.newBuilder();
        if (!TextUtils.isEmpty(cookie)) {
            builder.header("Cookie", cookie);
        }
        String method = request.method();
        if ("get".equalsIgnoreCase(method)) {
            String verify = verify(request.url().toString());
            builder.header("ax", verify);
        } else if ("post".equalsIgnoreCase(method)) {
            RequestBody body = request.body();
            assert body != null;
            MediaType mediaType = body.contentType();
            if (mediaType != null && "json".equalsIgnoreCase(mediaType.subtype())) {
                Buffer buffer = bufferThreadLocal.get();
                if (buffer == null) {
                    buffer = new Buffer();
                    bufferThreadLocal.set(buffer);
                }
                buffer.clear();
                body.writeTo(buffer);
                Buffer bufferEncryption=MyApplication.getInstance().encryptionRequest(buffer);
                if (bufferEncryption!=null){
                  builder.post(RequestBody.Companion.create(bufferEncryption.readString(StandardCharsets.UTF_8),mediaType));
                }
                String json = buffer.readString(StandardCharsets.UTF_8);
                String toVerify = request.url().toString() + json;
                String verify = verify(toVerify);
                builder.header("ax", verify);
            } else if (body.contentLength() == 0) {
                String verify = verify(request.url().toString());
                builder.header("ax", verify);
            }
        }
        request = builder.build();
        /*
         * -----------------↑↑↑ REQUEST ↑↑↑ ------- ----------
         */
        Response originalResponse = chain.proceed(request);

        /*
         * -----------------↓↓↓ RESPONSE ↓↓↓-----------------
         */
        List<String> headers = originalResponse.headers("Set-Cookie");
        for (String header : headers) {
            cookieManager.setCookie(originalResponse.request().url().toString(), header);
        }
        cookieManager.flush();
        return originalResponse;
    }
    //满足以后在加密需求
    private String verify(String content){
        return MyApplication.getInstance().urlVerify(content);
    }
}

